//
//  TWCorrelationCollectionView.swift
//  EyepetizerImitative
//
//  Created by 田伟 on 2017/3/27.
//  Copyright © 2017年 个人. All rights reserved.
//

import UIKit

class TWCorrelationCollectionView: UICollectionView {

    var tw_correlationModel : TWCorrelationModel?{
        didSet {
            guard let tw_correlationModel = tw_correlationModel else {
                return
            }
            tw_dataSource = tw_correlationModel.correlationitemList
        }
    }
    
    var tw_dataSource = [TWItemModel]()
    var flowLayout = UICollectionViewFlowLayout()
    
    
    override func awakeFromNib() {
        super.awakeFromNib()
        // 初始化布局
        let width = UIScreen.main.bounds.width * 0.7
        let height = width * 0.58 + 50
        flowLayout.itemSize = CGSize(width: width, height: height)
        flowLayout.minimumInteritemSpacing = 2
        flowLayout.scrollDirection = .horizontal
        
        // 初始化CollectionView
        collectionViewLayout = flowLayout
        backgroundColor = UIColor.clear
        showsHorizontalScrollIndicator = false
        delegate = self
        dataSource = self
        contentInset = UIEdgeInsets(top: 0, left: 20, bottom: 0, right: 0)
        contentOffset = CGPoint(x: -20, y: 0)
        register(UINib(nibName: "TWCorrelationCollectionCell", bundle: nil), forCellWithReuseIdentifier: CorrelationCollectionCell)
    }
}

extension TWCorrelationCollectionView : UICollectionViewDataSource, UICollectionViewDelegate {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return tw_dataSource.count
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: CorrelationCollectionCell, for: indexPath) as! TWCorrelationCollectionCell
        cell.model = tw_dataSource[indexPath.item]
        return cell
    }
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        // 点到哪个讲对应的model传递出去，隔了2层，使用通知
        var needDict = [String : AnyObject]()
        needDict["allArray"] = tw_dataSource as AnyObject?                  // 这一组模型
        needDict["itemModel"] = tw_dataSource[indexPath.item]               // 当前选中的模型
        // 传值
        NotificationCenter.default.post(name: NSNotification.Name(rawValue :CorrelationCollectionViewCellDidSeleted), object: needDict)
    }
}
